package com.example.captcha.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.example.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private final static Long VALID_TIME=60*30*1000L;
    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response,HttpSession session)  {
        response.setCharacterEncoding("UTF-8");
        // 修正为正确的图片类型
        response.setContentType("image/jpeg");

        try {
            //定义图形验证码的长、宽、验证码字符数、干扰线宽度
            ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(captchaProperties.getWidth(),captchaProperties.getHeight());
//ShearCaptcha captcha = new ShearCaptcha(200, 100, 4, 4);
            String code=captcha.getCode();
            System.out.println(code);
            session.setAttribute(captchaProperties.getSession().getKey(),code);
            session.setAttribute(captchaProperties.getSession().getDate(),new Date());
//图形验证码写出，可以写出到文件，也可以写出到流
            captcha.write(response.getOutputStream());
            ////验证图形验证码的有效性，返回boolean值
//        captcha.verify("1234");Http
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public Boolean check(String captcha, HttpSession session){

        // 判断captcha是否为空
        if(!StringUtils.hasLength(captcha)){
            return false;
        }
        // 从session中获取captcha对应的验证码
        String code= (String) session.getAttribute(captchaProperties.getSession().getKey());
        // 从session中获取captcha对应的日期
        Date date= (Date) session.getAttribute(captchaProperties.getSession().getDate());
        // 判断验证码是否正确，日期是否为空，以及验证码是否在有效期内
        if(captcha.equalsIgnoreCase(code)&&date!=null&&
                System.currentTimeMillis()-date.getTime()<VALID_TIME){
            return true;
        }
        return false;
    }
}
